package team.chuangshu.lm.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.*;
/*import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.*;*/
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import team.chuangshu.lm.dto.MessageDTO;
import team.chuangshu.lm.entity.*;
import team.chuangshu.lm.service.*;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController("/file")
@Slf4j
public class FileController {

    @Value("${PDFTemplateUrl}")
    private String PDFTemplateUrl;

    @Value("${PDFResultUrl}")
    private String PDFResultUrl;

    @Value("${ExcelTemplateUrl}")
    private String ExcelTemplateUrl;

    @Value("${ExcelResultUrl}")
    private String ExcelResultUrl;

    @Autowired
    private MessageService messageService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private ClazzService clazzService;

    @Autowired
    private FacultyService facultyService;


    //下载请假条pdf
    @GetMapping("/getMessagePDF")
    @ApiOperation("获取假条pdf文件，传入一个message队列")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "假条id",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "fileName",value = "文件名",required = true,dataType = "String")
    })
    public ResponseEntity<byte[]> getMessageExcle(String messageId, String fileName) throws  Exception{

        log.info("messageId ={}",messageId);
        Message message = messageService.get(messageId);
        if (message == null) {
            throw new RuntimeException("假条为空");
        }
        if (message.getStatus() == "0" | message.getStatus() == "2") {
            throw new RuntimeException("该假条还未通过申请");
        }
        log.info(message.toString());
        MessageDTO messageDTO = new MessageDTO(message);


        //补充老师信息
        Teacher teacher = new Teacher();
        teacher.setUserId(message.getTeacherId());
        teacher = teacherService.findByParams(teacher).get(0);
        messageDTO.setTeacherName(teacher.getName());
        messageDTO.setTeacherPhone(teacher.getPhone());
        //补充班级信息
        Student student = new Student();
        student.setUserId(message.getStudentId());
        List<Student> studentList = studentService.findByParams(student);
        Clazz clazz = clazzService.get(studentList.get(0).getClazzId());
        messageDTO.setClassName(clazz.getClazzName());
        //补充学院信息
        Faculty faculty = facultyService.get(clazz.getParentId());
        messageDTO.setFacultyName(faculty.getFacultyName());
        messageDTO.setFacultyTeacher(faculty.getName());
        //对象转换成map
        Map<String, String> map = new HashMap();

        if(messageDTO  != null){
            BeanInfo beanInfo = Introspector.getBeanInfo(messageDTO .getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(messageDTO);
                    System.out.println(key);
                    System.out.println(value);
                    if (value == null) {
                        value = "";
                    }
                    if (value instanceof java.util.Date) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        value = sdf.format(value);
                    }
                    map.put(key, value.toString());
                }
            }
        }

        if (messageDTO.getIsLongtime() == 0) {
            map.remove("facultyTeacher");
        }

        /*String templatePath = "fileTemplate/template.pdf";
        // 生成的新文件路径
        String newPDFPath = System.getProperty("user.dir")+"/static/main/resources/"+"fileTemplate/test.pdf";*/

        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        //BaseFont bf =BaseFont.createFont("C:/Windows/Fonts/SimSun.TTF,1",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        // BaseFont bf = BaseFont.createFont("宋体" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        //BaseFont bf = BaseFont.createFont();
        BaseFont bf =BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        //Font FontChinese = new Font(bf, 5, Font.NORMAL);
        Font FontChinese = new Font(bf, 5);
        log.info("pdf模板文件路径：{}",PDFTemplateUrl);
        log.info("pdf生成文件路径：{}",PDFResultUrl);
        out = new FileOutputStream(PDFResultUrl);// 输出流
        reader = new PdfReader(PDFTemplateUrl);// 读取pdf模板
        bos = new ByteArrayOutputStream();
        stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        //文字类的内容处理
        Map<String,String> datemap = map;
        form.addSubstitutionFont(bf);
        for(String key : datemap.keySet()){
            String value = datemap.get(key);
            form.setField(key,value);
        }

        stamper.setFormFlattening(true);// 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
        stamper.close();
        Document doc = new Document();
        Font font = new Font(bf, 32);
        PdfCopy copy = new PdfCopy(doc, out);
        doc.open();
        PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
        copy.addPage(importPage);
        doc.close();

        String[] getFileExtension = PDFResultUrl.split("\\.");
        fileName = fileName+"."+getFileExtension[getFileExtension.length-1];
        File file = new File(PDFResultUrl);
        HttpHeaders headers = new HttpHeaders();
        //少了这句，可能导致下载中文文件名的文档，只有后缀名的情况
        String downloadFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        //告知浏览器以下载方式打开
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //设置MIME类型
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //用FileUpload组件的FileUtils读取文件，并构建成ResponseEntity<byte[]>返回给浏览器
        //HttpStatus.CREATED是HTTP的状态码201
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }



    //导出假条excel
    @GetMapping("/getMessageExcle")
    @ApiOperation("获取假条excel文件，传出一个message队列")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "fileName",value = "文件名",required = true,dataType = "String")
    })
    public ResponseEntity<byte[]> getMessageExcle(@RequestParam(value = "messageIdList")List<String> messageIdList, String fileName) throws Exception {
        List<Message> messageList = new ArrayList<Message>();
        for (String s : messageIdList) {
            Message message = messageService.get(s);
            if (message != null) {
                messageList.add(message);
            }
        }

       /* String templateURL = System.getProperty("user.dir")+"/static/main/resources/"+"fileTemplate/tempalte.xls";
        String resultURl = System.getProperty("user.dir") + "/static/main/resources/" + "fileTemplate/test.xls";*/
        HSSFWorkbook wb1 = new HSSFWorkbook(new FileInputStream(new File(ExcelTemplateUrl)));

        //获取模板表
        HSSFSheet sheet = wb1.getSheetAt(0);

        //定义一个样式（模板中第一行第一列的样式）
        HSSFCellStyle cellStyle = sheet.getRow(0)
                .getCell(0)
                .getCellStyle();

        //获取模板列宽
        float width = sheet.getColumnWidthInPixels(sheet.getRow(0).getCell(0).getColumnIndex());

        //获取模板行高
        float height = sheet.getRow(0).getHeightInPoints();

        for (int i = 0; i < messageList.size(); i++) {
            HSSFRow row = wb1.getSheetAt(0).createRow(i + 1);
            Message message = messageList.get(i);
            //设置行高
            row.setHeightInPoints(height);
            //假条编号
            HSSFCell idCell = row.createCell(0);
            idCell.setCellValue(message.getMessageId());
            //请假学生
            HSSFCell nameCell = row.createCell(1);
            nameCell.setCellValue(message.getStudentName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            //假条开始时间
            HSSFCell beginTiCell = row.createCell(2);
            beginTiCell.setCellValue(sdf.format(message.getBeginTime()));
            //假条结束时间
            HSSFCell endTiCell = row.createCell(3);
            endTiCell.setCellValue(sdf.format(message.getEndTime()));
            //假条状态
            HSSFCell statusCell = row.createCell(4);
            String status = "";
            switch (message.getStatus()){
                case "0": status = "申请中"; break;
                case "1": status = "已批准"; break;
                case "2": status = "已拒绝"; break;
                case "3": status = "待销假"; break;
                case "4": status = "已申请销假"; break;
                case "5": status = "已销假"; break;
            }
            statusCell.setCellValue(status);
            //审批时间
            HSSFCell commintaTi = row.createCell(5);
            String conmmitTi ;
            if (message.getStatus().equals("0")) {
                conmmitTi = "";
            }else if (message.getStatus().equals("2")) {
                if (message.getLevelTwoComment() == null) {
                    conmmitTi = sdf.format(message.getLevelOneTime());
                }else {
                    conmmitTi = sdf.format(message.getLevelTwoTime());
                }
            }else {
                if (message.getIsLongtime() == 0) {
                    conmmitTi = sdf.format(message.getLevelOneTime());
                }else {

                    conmmitTi = sdf.format(message.getLevelTwoTime());
                }
            }
            commintaTi.setCellValue(conmmitTi);
            //需要销假标识
            HSSFCell reportSign = row.createCell(6);
            if (message.getIsReportback() == 0) {
                reportSign.setCellValue("否");
            }else {
                reportSign.setCellValue("是");
            }
        }
        FileOutputStream stream = new FileOutputStream(new File(ExcelResultUrl));
        wb1.write(stream);
        stream.close();
        String[] getFileExtension = ExcelResultUrl.split("\\.");
        fileName = fileName+"."+getFileExtension[getFileExtension.length-1];
        File file = new File(ExcelResultUrl);
        HttpHeaders headers = new HttpHeaders();
        //少了这句，可能导致下载中文文件名的文档，只有后缀名的情况
        String downloadFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        //告知浏览器以下载方式打开
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //设置MIME类型
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //用FileUpload组件的FileUtils读取文件，并构建成ResponseEntity<byte[]>返回给浏览器
        //HttpStatus.CREATED是HTTP的状态码201
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);//

    }



    //下载请假资料
    @GetMapping("/downloadMessageFile")
    @ApiOperation("下载请假信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "fileUrl",value = "数据库中存储的文件路径",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "fileName",value = "下载的文件名",required = true,dataType = "String")
    })
    public ResponseEntity<byte[]>downloadMessageFile (String fileUrl,String fileName) throws UnsupportedEncodingException {
        String[] split = fileUrl.split("/file/");
        String[] getFileExtension = fileUrl.split("\\.");
        log.info(getFileExtension[getFileExtension.length-1]);
        fileName = fileName+"."+getFileExtension[getFileExtension.length-1];
        String path = "/leaveMessage/file/" +split[1];
        try {
            File file = new File(path);
            HttpHeaders headers = new HttpHeaders();
            //少了这句，可能导致下载中文文件名的文档，只有后缀名的情况
            String downloadFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            //告知浏览器以下载方式打开
            headers.setContentDispositionFormData("attachment", downloadFileName);
            //设置MIME类型
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //用FileUpload组件的FileUtils读取文件，并构建成ResponseEntity<byte[]>返回给浏览器
            //HttpStatus.CREATED是HTTP的状态码201
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);//
        } catch (IOException e) {
            throw new RuntimeException("下载失败!");
        }
    }
}
